/**
* @author Cheng Liu
**/

#include "CinePlugin.h"
#include <fstream>
#include <string>
#include <sstream>
#include <ctime>

class LogWriter : public IPlugin { 
public:
	virtual void Initialize(IPluginFacade* Cine);
	virtual void Release();

	virtual void Activate();
	virtual void Deactivate();
	virtual bool HandleEvent(Events::Event * event);
private:
	IPluginFacade* cine;
	std::ofstream logFile;
};

void LogWriter::Initialize( IPluginFacade* Cine ) {
	cine = Cine;
	time_t ltime;
	time(&ltime);
	tm ptime;
	localtime_s(&ptime, &ltime);
	std::stringstream fname;
	fname << "log_" << 1900 + ptime.tm_year << "_" << ptime.tm_mon << "_" << ptime.tm_mday << ".txt";
	logFile.open(fname.str().c_str());
}

void LogWriter::Release() {
	logFile.close();
}

using namespace Events;
void LogWriter::Activate() {
	cine->AttachListener(OutputLogEvent::type(), this);
}

void LogWriter::Deactivate() {
	cine->ReleaseListener(this);
}

bool LogWriter::HandleEvent( Event * event ){
	if (event->GetType() == OutputLogEvent::type()) {
		time_t ltime;
		time(&ltime);
		tm ptime;
		localtime_s(&ptime, &ltime);
		logFile << "[" << ptime.tm_year+1900 <<"-"<<ptime.tm_mon <<"-" << ptime.tm_mday
			<<" " << ptime.tm_hour <<":" << ptime.tm_min << ":" << ptime.tm_sec
		    <<"] ";
		std::string s = ((OutputLogEvent*) event)->logMsg;
		while (s[s.size()-1] == '\r' || s[s.size()-1]=='\n') s.erase(s.size()-1);
		logFile << s << std::endl;
	}
	return false;
}

IPlugin* CreatePluginObject(){
	return new LogWriter();
}

void DestroyPluginObject(IPlugin * plugin){
	delete plugin;
}

const char* GetPluginName(){
	return "LogWriter";
}

int GetPluginVersion(){
	return -1;
}